package com.jrx.anytxn.customer.controller;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.customer.config.CouponConfig;
import com.jrx.anytxn.customer.dto.BaseApiReq;
import com.jrx.anytxn.customer.dto.coupon.CouponChargeOffReq;
import com.jrx.anytxn.customer.dto.coupon.CouponReq;
import com.jrx.anytxn.customer.dto.coupon.CouponTrialReq;
import com.jrx.anytxn.customer.dto.coupon.CouponTrialRes;
import com.jrx.anytxn.customer.dto.coupon.RightsExchangeLogRes;
import com.jrx.anytxn.customer.dto.rights.CustRightRes;
import com.jrx.anytxn.customer.dto.rights.CustomerRightRes;
import com.jrx.anytxn.customer.entity.TlCouponDetail;
import com.jrx.anytxn.customer.entity.TlRightsExchangeLog;
import com.jrx.anytxn.customer.service.ICustomerRightService;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.customer.service.IRightsExchangeLogService;
import com.jrx.anytxn.customer.service.ITlCouponDetailService;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.param.enums.RightsTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * @author lbz date 2020/8/3
 * @ClassName CustomerRightController 为客户提供查询权益相关数据
 **/
@Api(tags = "API客户相关权益信息")
@RestController
@RequestMapping(value = "/api/customer/customerRight")
public class CustomerRightController {

    private static final Logger logger = LoggerFactory.getLogger(CustomerRightController.class);

    @Autowired
    private ICustomerRightService customerRightService;
    @Autowired
    private IRightsExchangeLogService rightsExchangeLogService;
    @Autowired
    private ITlCouponDetailService tlCouponDetailService;
    @Autowired
    private CouponConfig couponConfig;
    @Autowired
    private ICustomerService customerService;

    @ApiOperation(value = "客户权益查询", notes = "客户权益查询")
    @PostMapping(value = "/queryCustomerRight")
    public TxnRespResult<CustomerRightRes> queryCustomerRight(@Valid @RequestBody BaseApiReq baseApiReq)
            throws TxnBizException {
        TxnRespResult<CustomerRightRes> result = new TxnRespResult<>();
        logger.info("客户权益查询开始:startTime:{}", result.getStartTime());
        result.getSuccess(customerRightService.getCustomerRight(baseApiReq));
        logger.debug("客户权益查询结束endTime{}", result.getEndTime());
        return result;
    }

    @ApiOperation(value = "获取客户权益资格列表", notes = "获取客户权益资格列表")
    @PostMapping(value = "/listCustomerRightQualification")
    public TxnRespResult<CustomerRightRes> listCustomerRightQualification(@Valid @RequestBody BaseApiReq baseApiReq) {
        String tenantId = baseApiReq.getTenantId();
        String userId = baseApiReq.getUserId();
        String channel = baseApiReq.getChannel();
        TxnRespResult<CustomerRightRes> result = new TxnRespResult<>();
        List<String> qualificationTypeList = new ArrayList<>(Arrays.asList(RightsTypeEnum.QUALIFICATION.getCode()));

        try {
            List<CustRightRes> custRightResList =
                    customerRightService.listByCustomerRightsType(userId, tenantId, channel, qualificationTypeList);
            CustomerRightRes customerRightRes = new CustomerRightRes();
            customerRightRes.setUserId(userId);
            customerRightRes.setTenantId(tenantId);
            customerRightRes.setChannel(channel);
            customerRightRes.setBusinessDate(new Date());
            customerRightRes.setCustRightList(custRightResList);
            result.getSuccess(customerRightRes);
        } catch (TxnBizException e) {
            result.getFail(e.getErrCode(), e.getErrMsg());
        }
        return result;
    }

    @ApiOperation(value = "获取客户优惠券列表", notes = "获取客户优惠券列表")
    @PostMapping(value = "/listCustomerRightCoupon")
    public TxnRespResult<CustomerRightRes> listCustomerRightCoupon(@Valid @RequestBody BaseApiReq baseApiReq) {
        String tenantId = baseApiReq.getTenantId();
        String userId = baseApiReq.getUserId();
        String channel = baseApiReq.getChannel();
        TxnRespResult<CustomerRightRes> result = new TxnRespResult<>();
        List<String> couponTypeList = new ArrayList<>(
                Arrays.asList(RightsTypeEnum.CASH_COUPON.getCode(), RightsTypeEnum.DISCOUNT_COUPON.getCode()));
        try {
            List<CustRightRes> customerRightInfoList =
                    customerRightService.listByCustomerRightsType(userId, tenantId, channel, couponTypeList);
            CustomerRightRes customerRightRes = new CustomerRightRes();
            customerRightRes.setUserId(userId);
            customerRightRes.setTenantId(tenantId);
            customerRightRes.setChannel(channel);
            customerRightRes.setBusinessDate(new Date());
            customerRightRes.setCustRightList(customerRightInfoList.stream()
                    .sorted(Comparator.comparing(CustRightRes::getExpiresDate)).collect(Collectors.toList()));
            result.getSuccess(customerRightRes);
        } catch (TxnBizException e) {
            result.getFail(e.getErrCode(), e.getErrMsg());
        }
        return result;
    }

    /**
     * 优惠券试算（现金优惠券、折扣优惠券）
     *
     * @param couponTrialReq
     * @return
     */
    @ApiOperation(value = "优惠券试算", notes = "优惠券试算")
    @PostMapping(value = "/couponTrial")
    public TxnRespResult<CouponTrialRes> couponTrial(@Valid @RequestBody CouponTrialReq couponTrialReq) {
        TxnRespResult<CouponTrialRes> result = new TxnRespResult<>();
        try {
            if (couponTrialReq.getTranAmt() == null) {
                throw new TxnBizException(TxnRespCode.TRAN_AMT_NULL);
            }
            result.getSuccess(customerRightService.couponTrial(couponTrialReq));
        } catch (TxnBizException e) {
            result.getFail(e.getErrCode(), e.getErrMsg());
        }
        return result;
    }

    @ApiOperation(value = "优惠券使用", notes = "优惠券使用")
    @PostMapping(value = "/couponChargeOff")
    public TxnRespResult<CouponTrialRes> couponChargeOff(@Valid @RequestBody CouponChargeOffReq couponChargeOffReq) {
        TxnRespResult<CouponTrialRes> result = new TxnRespResult<>();
        try {
            result.getSuccess(customerRightService.chargeOffCoupon(couponChargeOffReq));
        } catch (TxnBizException e) {
            result.getFail(e.getErrCode(), e.getErrMsg());
        }
        return result;
    }

    @ApiOperation(value = "权益兑换流水表", notes = "权益兑换流水表")
    @PostMapping(value = "/listRightsExchangeLog")
    public TxnRespResult<List<RightsExchangeLogRes>> listRightsExchangeLog(@RequestBody BaseApiReq baseApiReq) {
        TxnRespResult<List<RightsExchangeLogRes>> result = new TxnRespResult<>();
        try {
            result.getSuccess(rightsExchangeLogService.listByUserIdAndTenantIdAndChannel(baseApiReq.getUserId(),
                    baseApiReq.getTenantId(), baseApiReq.getChannel()));
        } catch (TxnBizException exception) {
            return result.getFail(exception.getErrCode(), exception.getErrMsg());
        }
        return result;
    }

    @ApiOperation(value = "查询客户活动领取详情", notes = "查询客户活动领取详情")
    @PostMapping("/listCustomerCouponDetailByActivity")
    public TxnRespResult<Integer> listCustomerCouponDetailByActivity(@RequestBody CouponReq couponReq) {
        TxnRespResult<Integer> result = new TxnRespResult();
        List<TlCouponDetail> couponDetailList;
        try {
            couponDetailList = tlCouponDetailService.findByUserIdAndActivityId(couponReq.getUserId(),
                    couponReq.getActivityId(), couponReq.getTenantId(), couponReq.getChannel());
        } catch (TxnBizException exception) {
            return result.getFail(exception.getErrCode(), exception.getErrMsg());
        }
        return result.getSuccess(couponDetailList.size());
    }

    @ApiOperation(value = "查询客户邀新分享活动战绩详情", notes = "查询客户邀新分享活动战绩详情")
    @PostMapping("/listRecommendCouponDetail")
    public TxnRespResult<Integer> listRecommendCouponDetail(@RequestBody CouponReq couponReq) throws TxnBizException {
        TxnRespResult<Integer> result = new TxnRespResult<>();
        String channel = couponReq.getChannel();
        String userId = couponReq.getUserId();
        String tenantId = couponReq.getTenantId();
        String mobile = couponReq.getMobile();
        try {
            customerService.getCustomerByChannelAndUserId(channel, userId, tenantId);
        } catch (TxnBizException exception) {
            // 分享者未激活心安花进行特殊处理~
            if (TxnRespCode.CUSTOMER_INFO_NOT_EXIST.getCode() == exception.getErrCode()) {
                logger.info("当前用户id:{}未激活", userId);
            } else {
                return result.getFail(exception.getErrCode(), exception.getErrMsg());
            }
        }

        List<TlRightsExchangeLog> rightsExchangeLogList = rightsExchangeLogService.listByChargeAccountAndRecommendedAndActivityIdAndTenantId(tenantId, mobile, null,
                couponConfig.getSharedFirstConsume());
        return result.getSuccess(rightsExchangeLogList.size());
    }

    /**
     * 去重
     * @param sourceList
     * @return
     */
    private List<TlRightsExchangeLog> removeRepetition(List<TlRightsExchangeLog> sourceList){
        if(sourceList == null){
            return Collections.emptyList();
        }
        return sourceList.stream()
                .collect(Collectors.collectingAndThen
                        (Collectors.toCollection(() ->
                                        new TreeSet<>(Comparator.comparing(t -> t.getRecommended()))),
                                ArrayList::new
                        )
                );
    }

}
